package com.cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.cn.domain.Comment;
import com.cn.domain.User;
import com.cn.service.CommentService;
import com.cn.service.UserService;
import com.cn.service.impl.CommentServiceImpl;
import com.cn.service.impl.UserServiceImpl;
import com.cn.utils.PageView;

@WebServlet("/AddCommentServlet")
public class AddCommentServlet extends HttpServlet {
	private CommentService cs=new CommentServiceImpl();
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Map<String,String[]> map=req.getParameterMap();
		Comment comment=new Comment();
		int currentPage=1;
		String pageNow=req.getParameter("pageNow");
		if(pageNow!=null) {
			currentPage=Integer.parseInt(pageNow);
		}
		int recordCount=cs.getAllCount().size();
		List<Comment> allComments=cs.commentList(currentPage,3);
		PageView pageView=new PageView(currentPage,recordCount,allComments);
		req.setAttribute("pageView", pageView);
		String type=req.getParameter("type");
		if("submitInfo".equals(type)) {
			try {
				//将登陆页面输入的信息封装user
				BeanUtils.populate(comment, map);
				if(cs.addComents(comment)>0) {
					resp.setHeader("refresh", "0;url=http://localhost:8088/amazon/AddCommentServlet");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		req.getRequestDispatcher("/guestbook.jsp").forward(req, resp);
	}
}
